<?php
# http://projects:8081/cdapp-2kt-api/api/seat_hours_load.php

include_once '_portal.php';
include_once 'request_atcos.php';
include_once 'seat_hours_load_users.php';

forbidden_acc();

# constants

const MIN_TTL = 5 * 60 * 1000; # ms
const MAX_TTL = 10 * 60 * 1000; # ms
const PARAM_NAME = 'seatHoursLoadTime';
const PARAM_NAME_USERS = 'ATCOSUsers';
const PARAM_NAME_USERS_GROUPED = 'ATCOSUsersGrouped';

# params for load

$dates = isset($post->dates) && $post->dates != null ? $post->dates : [date('Y-m-d')];
$forced = isset($post->forced) && $post->forced != null ? $post->forced : false;
$codes = isset($post->codes) && $post->codes != null ? $post->codes : ['TM01', 'TM02', 'TM03', 'TM04', 'TM05', 'TM06', 'TM07', 'TM08', 'TM09', 'TM10', 'TM11', 'TM12', 'TM13', 'TM14', 'OMA01', 'SUP01', 'SUP02', 'PLANNER'];

# params for get

$start = isset($_GET['start']) ? $_GET['start'] : date('Y-m-d');
$end = isset($_GET['end']) ? $_GET['end'] : date('Y-m-d');
$full = isset($_GET['full']) ? $_GET['full'] : 0;
$immediately = isset($_GET['immediately']) ? $_GET['immediately'] : 0;
$need_get = isset($_GET['start']) && isset($_GET['end']);

# get only
if ($need_get && $immediately) {
  output(get_hours($start, $end, $full));
  die();
}

# before refesh data, get last refresh information
$refresh_info = get_param(PARAM_NAME);

# if no refresh information, create a new one
if (!isset($refresh_info) || $refresh_info == null) {
  $refresh_info = ['tx' => 0, 'rx' => 0, 'sid' => 0];
  save_param(PARAM_NAME, $refresh_info);
}

$request_time = $refresh_info['tx'];
$response_time = $refresh_info['rx'];
$start_time = timestamp();

# >>> judgements if refresh is ineed
# ----------------------------------------
# [o] more than 3s after last response
# [x] no request sent more than 30s
# [x] no response time recorded

$ineed = false;
$ineed = $ineed || ($start_time - $response_time > MIN_TTL && $request_time < $response_time);
$ineed = $ineed || $start_time - $request_time > MAX_TTL;
$ineed = $ineed || !$response_time;

$output = null;

# if need for refresh, get new request information
if ($ineed || $forced) {
  $last_server_index = $refresh_info['sid'];
  $next_server_index = ($last_server_index + 1) % 3;

  # record time and server index of request
  $info = ['tx' => $start_time, 'rx' => $response_time, 'sid' => $next_server_index];
  save_param(PARAM_NAME, $info);

  # execute function query_working_hours
  $source = query_hours($next_server_index, $dates, $codes);
  if ($source['count'] > 0) {

    # if response is long enough, save it to database
    $result = exec_sql_array($source['sql']);

    # record time of response
    $end_time = timestamp();
    $info = ['tx' => $start_time, 'rx' => $end_time, 'sid' => $next_server_index];
    save_param(PARAM_NAME, $info);

    # load user list
    $result_user = load_atcos_users();

    # output successed result and exit
    $verbose = $forced ? [
      'loadResult' => $result,
      'userResult' => $result_user,
      'sourceResult' => $source,

    ] : null;
    $output = [
      'status' => 'success',
      'message' => 'refresh working hours successfully',
      'result' => !in_array(false, $result),
      'count' => $source['count'],
      'verbose' => $verbose,
    ];
  } else {
    # output failed result and exit
    $output = [
      'status' => 'failed',
      'message' => 'server inaccessible',
    ];
  }
} else {
  # output no need result and exit
  $output = ['status' => 'failed', 'message' => 'no need for refresh', 'lastInfo' => $refresh_info];
}

# response for get action
if ($need_get) {
  $get_result = get_hours($start, $end, $full);
  $output['start'] = $get_result['start'];
  $output['end'] = $get_result['end'];
  $output['count'] = $get_result['count'];
  $output['content'] = $get_result['content'];
  $output['users'] = $get_result['users'];
  $output['usersGrouped'] = $get_result['usersGrouped'];
}

# output result
output($output);
die();

function query_hours_disposed($server, $dates, $codes) {

  # default input values
  // $server = isset($server) && $server != null ? $server : -1;
  $dates = isset($dates) && $dates != null ? $dates : date('Y-m-d');
  $codes = isset($codes) && $codes != null ? $codes : ['TM01', 'TM02', 'TM03', 'TM04', 'TM05', 'TM06', 'TM07', 'TM08', 'TM09', 'TM10', 'TM11', 'TM12', 'TM13', 'TM14', 'OMA01', 'OMA02', 'SUP01', 'SUP02', 'PLANNER'];

  # generate request uris for working hours
  $content = [];
  $url_list = [];
  foreach ($codes as $code) {
    $url_list[] = "workingHours/getAllNotEndWorkingHours?seatCode={$code}";
  }
  foreach ($codes as $code) {
    foreach ($dates as $day) {
      $url_list[] = "workingHours/getAllWorkingHoursBySeatCodeAndDay?seatCode={$code}&day={$day}";
    }
  }
  $response = request_atcos($url_list);
  // output($response);
  $sql = [];
  $sql[] = "DELETE FROM `2kt_seat_hours` WHERE `endTime` IS NULL";
  $sql[] = "INSERT IGNORE INTO `2kt_seat_hours`(`recordID`, `userName`, `userId`, `startTime`, `endTime`, `seatCode`, `sectorCodes`, `seatRole`, `seatPost`, `qualification`, `controlLevel`) VALUES ";

  # for each content
  if (isset($response) && is_array($response) && count($response) > 0) {
    for ($i = 0; $i < count($response); $i++) {
      if (isset($response[$i]) && is_array($response[$i]) && count($response[$i]) > 0) {
        for ($j = 0; $j < count($response[$i]); $j++) {
          $cell = [
            'recordID' => $response[$i][$j]['id'],
            'userName' => $response[$i][$j]['userName'],
            'userId' => $response[$i][$j]['userId'],
            'startTime' => $response[$i][$j]['startTime'],
            'endTime' => $response[$i][$j]['endTime'],
            'seatCode' => $response[$i][$j]['seatCode'],
            'sectorCodes' => $response[$i][$j]['sectorCodes'],
            'seatRole' => trim($response[$i][$j]['seatRole']['name']),
            'seatPost' => trim($response[$i][$j]['seatPost']['name']),
            'qualification' => trim($response[$i][$j]['qualification']['name']),
            'controlLevel' => trim($response[$i][$j]['controlLevel']['name']),
          ];
          $content[] = $cell;
          $startTime = $cell['startTime'] == null ? 'NULL' : "'{$cell['startTime']}'";
          $endTime = $cell['endTime'] == null ? 'NULL' : "'{$cell['endTime']}'";
          // $sql[] = "INSERT INTO `2kt_seat_hours`(`recordID`, `userName`, `userId`, `startTime`, `endTime`, `seatCode`, `sectorCodes`, `seatRole`, `seatPost`, `qualification`, `controlLevel`) VALUES ({$cell['recordID']},'{$cell['userName']}',{$cell['userId']},$startTime,$endTime,'{$cell['seatCode']}','{$cell['sectorCodes']}','{$cell['seatRole']}','{$cell['seatPost']}','{$cell['qualification']}','{$cell['controlLevel']}') ON DUPLICATE KEY UPDATE `endTime` = $endTime";
          $sql[1] .= "({$cell['recordID']},'{$cell['userName']}',{$cell['userId']},$startTime,$endTime,'{$cell['seatCode']}','{$cell['sectorCodes']}','{$cell['seatRole']}','{$cell['seatPost']}','{$cell['qualification']}','{$cell['controlLevel']}'),";
        }
      }
    }
  }
  $sql[1] = rtrim($sql[1], ',');

  # return query result
  return [
    'count' => count($content),
    'content' => $content,
    'sql' => $sql,
  ];
}

function query_hours() {
  return null;
}
function get_hours($start, $end, $full) {

  $colunms = $full ? '*' : '`userName`, `startTime`, `endTime`, `seatCode`, `seatRole`, `seatPost`';

  $sql = "SELECT {$colunms} FROM `2kt_seat_hours` WHERE `startTime` <= '{$end} 23:59:59' AND (`endTime` > '{$start} 00:00:00' OR `endTime` IS NULL)";

  $result = exec_sql($sql);

  $users = get_param(PARAM_NAME_USERS);
  $users_grouped = get_param(PARAM_NAME_USERS_GROUPED);

  $output = [
    'start' => $start,
    'end' => $end,
    'count' => count($result),
    'content' => $result,
    'users' => $users,
    'usersGrouped' => $users_grouped,
    // 'sql' => $sql,
  ];

  return $output;
  // output($output);
}